package testtimer;

import java.io.Serializable;
import java.util.Collection;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;

import dao.InterviewDAORemote;

/**
 * Session Bean implementation class TestTimerBean
 */

@Stateless
public class TestTimerBean implements TestTimerBeanRemote {

	@Resource
	TimerService timerService;
	
	@EJB
	InterviewDAORemote idr;
	
    public TestTimerBean() {
    }

    @Override
    public void startTimer(Serializable info) {
		System.out.println("Timer started: " + info);
		int intId = Integer.parseInt(info.toString());
		int nrOfMinutes = idr.getInterviewDuration(intId);
		System.out.println("Number of minutes: " + nrOfMinutes);
		timerService.createTimer(nrOfMinutes * 1000 * 60, info);
    }
    
    public void stopTimer(Serializable info) {
		Timer timer = null;
		Collection<Timer> timers = timerService.getTimers();
		System.out.println("Time remaining: " + this.checkStatus(info));
		for (Object o : timers) {
			timer = ((Timer) o);
			if (timer.getInfo().equals(info)) {
				timer.cancel();
			}
 		}
		System.out.println("TestTimerBean stopped. ");
	}
    
    public long checkStatus(Serializable info) {
	  Collection<Timer> timers = timerService.getTimers();
	  for (Timer timer : timers) {
		  if (timer.getInfo().equals(info)) {
			  return timer.getTimeRemaining();
		  }
	  }
	  return -1;
    }
    
    @Timeout
    public void finishTestForUser(Timer t) {
    	System.out.println(t.getTimeRemaining());
    	System.out.println("TIMEOUT");
    }
}
